package com.jiecao.news.jiecaonews.backgroung;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jsoup.helper.StringUtil;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.jiecao.news.jiecaonews.dao.NewsDao;
import com.jiecao.news.jiecaonews.util.SharedPreferencesUtil;
/**
 * 强制刷新
 * @author lidongwei
 *
 */
public class FlushTask  extends AsyncTask<String, String, Void> {
	private static final String TAG = "FushTask";
	private String mUrl;
	private String mdate;
	private NewsDao mnewsDao;
	private Context mcontext;
	private String rdate;
	public FlushTask(String url,String date,Context context){
		mUrl = url;
		mdate = date;
		mcontext = context;
		mnewsDao =new NewsDao(context);
	}

	@Override
	protected Void doInBackground(String... params) {
		try {
			rdate = getFlushInfo(mUrl);
			System.out.println("FlushTask mdate"+rdate);
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return null ;
	}

	@Override
	protected void onPostExecute(Void result){
		//删除数据库中数据,保存数据到sharep
		if(!StringUtil.isBlank(rdate)&&(rdate.compareTo(mdate)>0)){
			System.out.println("in flush");
			SharedPreferencesUtil.writeFlushDate(mcontext, rdate);
			mnewsDao.flush();
		}
		
	}
	/**
	 * 
	 * 获取强制刷新参数
	 * @param url
	 * @return
	 * @throws IOException
	 */
	private String getFlushInfo(String url) throws IOException {
		URL target = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) target.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Content-Type", "text/html;");
		conn.setRequestProperty("Accept", "text/html;");
		conn.setConnectTimeout(5000);//设置5秒超时
		conn.connect();
		int code = conn.getResponseCode();
		System.out.println("code:" + code);
		if(!((code >= 200) && (code < 300))){
			return null;
		}
		
		InputStream in =  conn.getInputStream() ;
		StringBuilder sb = new StringBuilder();
//		HttpClient client = new DefaultHttpClient();
//		HttpParams httpParams = client.getParams();
//		// 设置网络超时参数
//		HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
//		HttpConnectionParams.setSoTimeout(httpParams, 5000);
		try {
//			HttpResponse response = client.execute(new HttpGet(url));
//			HttpEntity entity = response.getEntity();
				// 取出回应字串
				if (in != null) {
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(in, "UTF-8"),
							8192);
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					reader.close();
				}
		} catch (Exception e) {
			Log.e(TAG, "getFlushInfo error!" + e.getMessage());
			e.printStackTrace();
			return sb.toString();
		}
		return sb.toString();
	}
}
